package com.example.courier.service.impl;

import com.example.common.enetiy.User;
import com.example.courier.common.enums.DeliveryStatus;
import com.example.courier.entity.DeliveryOrder;
import com.example.courier.entity.Location;
import com.example.courier.mapper.DeliveryOrderMapper;
import com.example.courier.mapper.LocationMapper;
import com.example.courier.model.req.DeliveryOrderDTO;
import com.example.courier.model.resp.DeliveryOrderVO;
import com.example.courier.service.DeliveryOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author qwert
 * @version 1.0.0
 * @create 2025/9/6 15:25
 **/
@Service
@RequiredArgsConstructor
public class DeliveryOrderServiceImpl implements DeliveryOrderService {

    private final LocationMapper locationMapper;
    private final DeliveryOrderMapper deliveryOrderMapper;
    @Override
    public void createDeliveryOrder(DeliveryOrderDTO deliveryOrderDTO) {
        // 查询用户是否存在

        // 查询送货地址 和 送货地址
        String deliveryAddress = deliveryOrderDTO.getDeliveryAddress();
        String pickupAddress = deliveryOrderDTO.getPickupAddress();
        Location deliveryLocation = locationMapper.queryLocationById(deliveryAddress);
        Location pickupLocation = locationMapper.queryLocationById(pickupAddress);
        if (deliveryLocation == null || pickupLocation == null ) {
            throw new RuntimeException("地址信息有误");
        }

        // 判断预约时间是否合理

        // 保存 deliveryOrder
        String deliveryOrderId = UUID.randomUUID().toString();
        DeliveryOrder deliveryOrder = DeliveryOrder.builder()
                .deliveryOrderId(deliveryOrderId)
                .requesterId(deliveryOrderDTO.getRecipientId())
                .pickupAddress(pickupAddress)
//                .pickupDetails(deliveryOrderDTO.getDeliverDetails())
                .deliveryAddress(deliveryAddress)
//                .deliveryDetails(deliveryOrderDTO.getDeliverDetails())
                .goodsType("default")
                .status("0")
                .fee(100L)
                .createTime(System.currentTimeMillis() / 1000)
                .scheduledTime(deliveryOrderDTO.getTimestamp())
                .note("")
                .pickupCode("A1E2F3")
                .deliveryProof("https://mock-url.com")
                .isPaid(true)
                .build();
        deliveryOrderMapper.saveDeliveryOrder(deliveryOrder);
    }

    @Override
    public List<DeliveryOrderVO> getDeliveryOrderByUserId(String userId) {
        List<DeliveryOrder> deliveryOrders = deliveryOrderMapper.queryDeliveryOrderByPrams
                (userId, null, null, null);
        return covertToDeliverOrderVO(deliveryOrders);
    }

    @Override
    public List<DeliveryOrderVO> getStartToEndOrders(String startLocationId, String endLocationId, String status) {
        DeliveryStatus deliveryStatus = DeliveryStatus.getDeliveryStatus(status);
        List<DeliveryOrder> deliveryOrders = deliveryOrderMapper.queryDeliveryOrderByPrams(null, startLocationId, endLocationId, deliveryStatus.getStatus());
        return covertToDeliverOrderVO(deliveryOrders);
    }

    @Override
    public void changeOrders(String courierId, List<String> orderIds, DeliveryStatus deliveryStatus) {
        if (deliveryStatus.equals(DeliveryStatus.IN_PROGRESS)) {
            // 先抢占orderIds，然后锁定订单
            List<DeliveryOrder> deliveryOrders = deliveryOrderMapper.queryDeliveryOrderStatus(orderIds);
            if (deliveryOrders.isEmpty()) {
                throw new RuntimeException("订单状态不见了，请重试！");
            }

            for (DeliveryOrder deliveryOrder : deliveryOrders) {
                deliveryOrder.setCourierId(courierId);
                deliveryOrder.setStatus(DeliveryStatus.IN_PROGRESS.getStatus());
            }

            deliveryOrderMapper.acceptOrders(deliveryOrders);
        } else if (deliveryStatus.equals(DeliveryStatus.DELIVERED)){
            List<DeliveryOrder> deliveryOrders = deliveryOrderMapper.queryDeliveryOrderProgressing(courierId, orderIds, DeliveryStatus.IN_PROGRESS.getStatus());
            if (deliveryOrders.isEmpty()) {
                throw new RuntimeException("订单送达出错，请刷新重试！");
            }
            List<String> completeOrderIds = deliveryOrders.stream().map(DeliveryOrder::getDeliveryOrderId).toList();
            deliveryOrderMapper.completeOrders(completeOrderIds, deliveryStatus.getStatus());
        }

    }

    private List<DeliveryOrderVO> covertToDeliverOrderVO(List<DeliveryOrder> deliveryOrders) {
        Map<String, User> userInfo = User.getUserInfo();
        return deliveryOrders.stream().map(deliveryOrder -> DeliveryOrderVO.builder()
                .id(deliveryOrder.getDeliveryOrderId())
                .requesterId(deliveryOrder.getRequesterId())
                .requesterName(userInfo.get(deliveryOrder.getRequesterId()).getUsername())
                .requesterPhone(userInfo.get(deliveryOrder.getRequesterId()).getPhone())
                .courierId(deliveryOrder.getCourierId())
                .courierName(deliveryOrder.getCourierId() == null ? "待接单" : userInfo.get(deliveryOrder.getCourierId()).getUsername())
                .courierPhone(deliveryOrder.getCourierId() == null ? "" : userInfo.get(deliveryOrder.getCourierId()).getPhone())
                .status(deliveryOrder.getStatus())
                .pickupAddress(deliveryOrder.getPickupAddress())
                .pickupDetails(deliveryOrder.getPickupDetails())
                .deliveryAddress(deliveryOrder.getDeliveryAddress())
                .deliveryDetails(deliveryOrder.getDeliveryDetails())
                .scheduledTime(deliveryOrder.getScheduledTime())
                .completedTime(System.currentTimeMillis() / 1000)
                .createTime(deliveryOrder.getCreateTime())
                .build()
        ).toList();
    }
}
